package com.platform.web.controller;

import com.platform.common.base.BackJsonBean;
import com.platform.common.constants.Constants;
import com.platform.common.constants.UserConstants;
import com.platform.common.utils.BackJsonBeanUtil;
import com.platform.web.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author prngshuiming
 * @date: 2018/6/10 21:46
 */
@RequestMapping("/")
@RestController
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    IUserService userService;

    @RequestMapping(value = "/login.json", produces = "application/json;charset=UTF-8")
    public BackJsonBean login(HttpServletRequest request){
        int status =1 ;
        String desc ="登录失败,未知错误!";
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        if(StringUtils.isBlank(account)){
            desc = "请输入账号";
            return BackJsonBeanUtil.getBackJsonBean(status,desc,"",null);
        }
        if(StringUtils.isBlank(password)){
            desc = "请输入密码";
            return BackJsonBeanUtil.getBackJsonBean(status,desc,"",null);
        }
        //登录
        try {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        subject.login(token);
        request.getSession().setAttribute(Constants.JSESSIONID, SecurityUtils.getSubject().getSession().getId());
        status = 1;
        desc ="登陆成功!";
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            status = 0;
            desc = "账号或密码错误！";
            logger.error(e.getMessage(), e);
        } catch (LockedAccountException e) {
            status = 0;
            desc = "您的账号已被冻结了！";
            logger.error(e.getMessage(), e);
        } catch (Exception e) {
            status = 0;
            desc = "登录失败，遇到未知错误！";
            logger.error(e.getMessage(), e);
        }
        return BackJsonBeanUtil.getBackJsonBean(status,desc,"",null);
    }
}
